package com.liuzy.test;

import lombok.extern.slf4j.Slf4j;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

@Slf4j
public class BlockUtil {
    // 默认分块大小
    public static final long DEF_BLOCK_SIZE = 1024 * 1024 * 1; // 1M
    // 4位序号
    public static String leftPad(long block) {
        String s = "000" + block;
        return s.substring(s.length() - 4);
    }

    // 切几块
    public static int slice(long length, long size) {
        return (int) Math.ceil(1D * length / size);
    }

    // 切块
    public static List<Block> slices(String src) {
        return slices(src, DEF_BLOCK_SIZE);
    }

    public static List<Block> slices(String src, long size) {
        File file = new File(src);
        long offset = 0;
        long length = file.length();
        int count = slice(length, size);
        List<Block> blocks = new ArrayList<>(count);
        for (int i = 0; i < count; i++) {
            Block block = new Block(file);
            block.setBlock(i + 1);
            block.setOffset(offset);
            if (i == count - 1) { // 最后一块
                block.setLength(length - offset);
            } else {
                block.setLength(size);
            }
            blocks.add(block);
            offset += size;
        }
        return blocks;
    }
}
